package com.example.springbootjwtexample.koal;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

public class ByteUtil {

    public static String byteToBase64(byte[] bytes){

        return new String(Base64.encodeBase64(bytes));
    }

    public static byte[] base64ToByte(String base64String){
        return Base64.decodeBase64(base64String);
    }

    public static String byteToHexString(byte[] bytes){
        return Hex.encodeHexString(bytes);
    }

    public static byte[] hexToByte(String hex) throws DecoderException {
        return Hex.decodeHex(hex.toCharArray());
    }

    public static String stringToHexString(String content){
        return byteToHexString(content.getBytes());
    }

    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    public static String base64UrlEncode(byte[] simple) {	String s = new String(Base64.encodeBase64(simple)); // Regular base64 encoder
        s = s.split("=")[0]; // Remove any trailing '='s
        s = s.replace('+', '-'); // 62nd char of encoding
        s = s.replace('/', '_'); // 63rd char of encoding
        return s;
    }

    public static byte[] base64UrlDecode(String cipher) {
        String s = cipher;
        s = s.replace('-', '+'); // 62nd char of encoding
        s = s.replace('_', '/'); // 63rd char of encoding
        switch (s.length() % 4) { // Pad with trailing '='s
            case 0:
                break; // No pad chars in this case
            case 2:
                s += "==";
                break; // Two pad chars
            case 3:
                s += "=";
                break; // One pad char
            default:
                System.err.println("Illegal base64url String!");
        }
        return Base64.decodeBase64(s); // Standard base64 decoder
    }
}
